package com.lysj.bhp.scheduled.job;


import com.lysj.bhp.scheduled.base.ScheduledContent;
import com.lysj.bhp.scheduled.domain.BitCoinWallet;
import com.lysj.bhp.scheduled.domain.EthereumWallet;
import com.lysj.bhp.scheduled.domain.RechargeRecord;
import com.lysj.bhp.scheduled.domain.User;
import com.lysj.bhp.scheduled.util.BlockChainUtil;
import com.lysj.bhp.scheduled.util.EtherScanUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Random;

@Component
public class BitcoinJob extends ScheduledContent {

    private static Logger logger = LoggerFactory.getLogger(BitcoinJob.class);

    /*第一次10秒后执行，当执行完后0.2秒再执行，保证一秒并发不超过5个*/
    @Scheduled(initialDelay = 10000, fixedDelay = 500)
    public void queryBitcoinWallet() {
        logger.info("BitcoinJob is Starting ...");
        BitCoinWallet bitCoinWallet = bitcoinWalletRepository.findFirstByOrderByLastQueryTimeAsc();
        if (bitCoinWallet == null) {
            return;
        }
        long result = BlockChainUtil.getBitCoinBalance(bitCoinWallet.getGuid(), bitCoinWallet.getPassword());
        if (result < 0) { // !!!即使发生错误,也应该继续执行下一次的查询!!!
            logger.error("Blockchain return -1,bitcoinWalletId is " + bitCoinWallet.getBitcoinWalletId());
            bitCoinWallet.setLastQueryTime(System.currentTimeMillis());
            bitcoinWalletRepository.save(bitCoinWallet);
            return;
        }
        double realBalance = result * 1.0 / 100000000;
        if (BigDecimal.valueOf(realBalance).compareTo(bitCoinWallet.getBookKeepBalance()) == 1) { //查询到的余额大于钱包得真实余额(记账余额)，则更新
            logger.info("BitcoinWallet Balance Increment,Start Record!" + bitCoinWallet.getBitcoinWalletId());
            BigDecimal increase = BigDecimal.valueOf(realBalance).subtract(bitCoinWallet.getBookKeepBalance()); // 增加的余额
            bitCoinWallet.setBalance(bitCoinWallet.getBalance().add(increase));//更新钱包的总额
            bitCoinWallet.setAvailBalance(bitCoinWallet.getAvailBalance().add(increase));//更新钱包的可用余额
            // 创建充值记录
            RechargeRecord rechargeRecord = new RechargeRecord();
            rechargeRecord.setCoinType(10);
            rechargeRecord.setPayAmount(increase);
            rechargeRecord.setUserId(bitCoinWallet.getUserId());
            rechargeRecord.setCreateTime(new Date());
            rechargeRecord.setAuthentication("成功");
            rechargeRecord.setName("BTC");
            rechargeRecord.setChineseName("比特币");
            rechargeRecord.setAddress("0x" + bitCoinWallet.getLastAddress());
            rechargeRecordRepository.save(rechargeRecord);
        }
        bitCoinWallet.setBookKeepBalance(BigDecimal.valueOf(realBalance));//更新钱包的记账余额
        bitCoinWallet.setLastQueryTime(System.currentTimeMillis()); // 将最近的查询时间设置为现在
        bitcoinWalletRepository.save(bitCoinWallet);
    }


}
